import React, { useEffect, useState } from 'react'
import "./style.less"
import {withRouter} from "react-router-dom"
import {useDispatch, useStore} from "react-redux"
import * as collectActions from "../../../redux/actions/collect"

function BuyAndStoreView(props) {
  // console.log(props.id);
  const dispatch = useDispatch()
  const [isCollect,setIsCollect] = useState(false)

  // 初始化操作
  useEffect(()=>{
    setIsCollect(isStore())
  },[])

  const storeHandle = () =>{
    if(props.user.token) {
      // 判断用户是否收藏 1.收藏则取消 2.未收藏则收藏
      if(isStore()) {
        // 已收藏
        // console.log("已收藏");
        setIsCollect(true)
        dispatch(collectActions.removeCollect(props.id))
      }else {
        // 未收藏 
        // console.log("未收藏");
        setIsCollect(false)
        dispatch(collectActions.setCollect(props.id))
      }
    }else {
      // 请登录
      props.history.push("/login")
    }
  }

  // 用户收藏判定
  function isStore() {
    let collects = props.collects
    let id = props.id
    return collects.some(item =>{
      return item === id
    })
  }

  return (
    <div className="buy-store-container clear-fix">
      <div className="views"></div>
      <div className="item-container float-left">
        {
          isCollect ? 
          <button className="selected o" onClick={storeHandle}>已收藏</button>
          :
          <button className="selected" onClick={storeHandle}>收藏</button>
        }
      </div>
      <div className="item-container float-right">
        <button className="selected">购买</button>
      </div>
    </div>
  )
}

export default withRouter(BuyAndStoreView)
